package server;

import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;


import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * netty 服务端监听类
 */
public class ServerHandler extends ChannelHandlerAdapter {


    /**
     * 所有链接用户
     */
    public static final ConcurrentMap<String, Channel> channels = new ConcurrentHashMap<String, Channel>();

    /**
     * 连接成功
     * @param ctx
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        String channelId = ctx.channel().id().asLongText();
        Channel channel = ctx.channel();
        // 添加连接用户
        channels.put(channelId, channel);
        System.out.println("用户: " + channelId + "连接成功, 当前连接用户: " + channels.size());
        // 响应连接成功数据
        sendMsg(ctx.channel().id().asLongText(), "已成功连接 xj-netty 服务器");
    }


    /**
     * 当通道被调用, 执行方法(拿到数据)
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        // 获取请求数据
        String value = (String) msg;
        System.out.println("request msg: " + value);
        // 响应数据
        // ctx.writeAndFlush("hello 6666");
        sendMsg(ctx.channel().id().asLongText(), "服务端已接收: " + value);
    }

    /**
     * 连接断开
     * @param ctx
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 删除连接用户
        String channelId = ctx.channel().id().asLongText();
        channels.remove(channelId);
        System.out.println("用户: " + channelId + "端口连接关闭");
        // 关闭连接
        super.channelInactive(ctx);
    }

    /**
     * 连接异常断开
     * @param ctx
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // 关闭
        cause.printStackTrace();
        ctx.close();
    }


    /**
     *  发送消息
     * @param channelId 连接Id/用户Id
     * @param msg 发送的消息
     * @date 2024/11/27 16:05
     * @return void
     */
    public static void sendMsg(String channelId, String msg) {
        Channel channel = channels.get(channelId);
        channel.writeAndFlush(Unpooled.wrappedBuffer((msg).getBytes()));
    }
}